package org.bpms.job;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.bpms.model.wechat.Weixin;
import org.bpms.service.admin.MemberService;
import org.bpms.service.wechat.WeixinService;

import com.jfinal.aop.Enhancer;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.UserApi;

/**
 * 测试简单任务调度
 * @author hupei
 *
 */
public class JobA implements Runnable{
	private WeixinService weixinService = Enhancer.enhance(WeixinService.class);
	private MemberService memberService = Enhancer.enhance(MemberService.class);
	private Log log = Log.getLog(JobA.class);
	@Override
	public void run() {
		System.out.println("开始同步微信用户...");
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
		ApiResult result =  UserApi.getFollows();
		com.alibaba.fastjson.JSONObject obj = result.get("data");
		for (Object openid : obj.getJSONArray("openid")){
			ApiResult apiResult = UserApi.getUserInfo((String)openid);
			memberService.saveOrUpdate(apiResult);
		}	
		System.out.println("微信用户同步完成...");
	}
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		Prop p = PropKit.use("config.properties");
		Weixin weixin = weixinService.find();
		if (null != weixin){
			// 配置微信 API 相关常量
			ac.setAppId(weixin.getStr("appid"));
			ac.setAppSecret(weixin.getStr("appsecret"));
			ac.setToken(weixin.getStr("token"));
			if (null != weixin.getStr("encodingaeskey") && !weixin.getStr("encodingaeskey").equals("")){
				ac.setEncryptMessage(true);
				ac.setEncodingAesKey(weixin.getStr("encodingaeskey"));
			}
			if (p.getBoolean("redis_mode")){
				ac.setIsredis(true);
			}
			return ac;
		}
		return null;
	}
}
